# encoding: utf-8
# Copyright 2012, Google Inc. All Rights Reserved.
"""
Template serving handler. Returns a template file in the "templates" subdirectory.
Will pass through anything passed as a query string on the URL.

TODO: Need to use memcache to serve from memory rather than django templates
"""
__author__ = 'davidthorpe@google.com'

import sys,os,logging
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

# import local libraries
sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))
import constants

class TemplateHandler(webapp.RequestHandler):
	def query_string(self):
		query_string = self.request.query_string
		if query_string:
			return "?%s" % query_string
		else:
			return ""

	def template_path(self,name):
		if not name:
			name = "default"
		path = os.path.join(constants.TEMPLATE_PATH,"%s.html" % name)
		logging.debug("template_path: %s => %s" % (name,path))
		if not os.path.isfile(path):
			logging.error("Template not found: %s" % path)
			raise cache.FileNotFound("%s" % self.request.url)
		return path

	def get(self,name):
		try:
			# TODO: retrieve from memcache for <name,querystring> hash where not changed
			template_path = self.template_path(name)
			self.response.out.write(webapp.template.render(template_path,{ 'querystring': self.query_string() }))
		except cache.FileNotFound, e:
			self.error(404)
			self.response.headers['Content-Type'] = "text/plain"
			self.response.out.write("Resource not found: %s\n\n" % e)
		except Exception, e:
			self.error(500)
			self.response.headers['Content-Type'] = "text/plain"
			self.response.out.write("Server Error: %s\n\n" % e)
			
class AdminHandler(TemplateHandler):
	def get(self,name):
		try:
			template_path = self.template_path(name)
			admin_path = self.template_path("admin")
			self.response.out.write(webapp.template.render(admin_path,{ 'name': name }))
		except cache.FileNotFound, e:
			self.error(404)
			self.response.headers['Content-Type'] = "text/plain"
			self.response.out.write("Resource not found: %s\n\n" % e)
		except Exception, e:
			self.error(500)
			self.response.headers['Content-Type'] = "text/plain"
			self.response.out.write("Server Error: %s\n\n" % e)

application = webapp.WSGIApplication([
	(r'/()',TemplateHandler),
	(r'/(\w+)\.html',TemplateHandler),
	(r'/admin()',AdminHandler),
	(r'/admin/(\w+)\.html',AdminHandler),
	
],debug=constants.DEBUG)

def main():
	if constants.DEBUG:
		logging.getLogger().setLevel(logging.DEBUG)
	else:
		logging.getLogger().setLevel(logging.INFO)
	run_wsgi_app(application)

if __name__ == "__main__":
	main()
